package web.services;

import web.search.IndexHolder;
import web.search.SearchHelper;
import web.search.Searchable;
import web.util.DateUtil;
import com.feelafter.index.bean.SuccessNewsXm;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tool.GetLocationFromTitle;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/9/29.
 */
@Service
public class AdminLuceneSearchService {
    @Autowired
    private PropertyAnalyst propertyAnalysts;
    @Autowired
    private LocationService locationService;

    private final static Logger LOGGER = Logger.getLogger("AdminLuceneSearchService.class");

//    static IndexHolder holder_0;
    static IndexHolder holder_1;

    private String index=null;
    private String index_1=null;

//    初始化索引
    private synchronized void getHolder(){

        if(index_1==null){
            index_1=propertyAnalysts.getIndexUrl_1();
        }
        if(index==null){
            index=propertyAnalysts.getIndexUrl();
        }
        if (holder_1 ==null){
            try {
//                holder_0 = IndexHolder.init(index);
                holder_1 = IndexHolder.init(index_1);
            } catch (Exception e) {
                LOGGER.error("索引位置不对,切换索引位置:"+index_1);
            }
        }
    }

    /**
     * 通过招标公司与中标公司查询相关中标信息
     * @param subscriber
     * @param winBidCompany
     * @return
     */
    public List<Map<String,Object>> findSuccessfulNewsSubscriber(String subscriber , String winBidCompany){
//        初始化索引
        getHolder();
//        搜索条件
        Query query=null;
//        创建搜索条件
        List<String> queriList=new ArrayList<String>();
        List<String> fieldList=new ArrayList<String>();
        List<BooleanClause.Occur> flagList=new ArrayList<BooleanClause.Occur>();
        //添加搜索数据-招标单位
        if(!StringUtils.isBlank(subscriber)){
            queriList.add(subscriber);
            fieldList.add("subscriber");
            flagList.add(BooleanClause.Occur.MUST);
        }
        //添加搜索数据-中标单位
        if(!StringUtils.isBlank(winBidCompany)){
            queriList.add(winBidCompany);
            fieldList.add("win_bid_company");
            flagList.add(BooleanClause.Occur.MUST);
        }
//        拼接条件
        query = SearchHelper.makeQuery(fieldList.toArray(new String[fieldList.size()]), queriList.toArray(new String[queriList.size()])
                , flagList.toArray(new BooleanClause.Occur[flagList.size()]), 1.0f);
//        搜索实体类
        List<Class<? extends Searchable>> list = new ArrayList<Class<? extends Searchable>>();
        list.add(SuccessNewsXm.class);
        List<Searchable> newsList=null;
        try {
            newsList = holder_1.find(list, query, null, new Sort(new SortField[]{new SortField("stime", SortField.Type.INT, true)}), 1, 500);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        if(newsList.size()>0){
//            System.out.println(subscriber+"--"+winBidCompany);
//        }
        List<Map<String,Object>> listNews=new ArrayList<Map<String, Object>>();
        for (Searchable searchable : newsList) {
            SuccessNewsXm successNewsXm=(SuccessNewsXm)searchable;
            Map<String,Object> map=new HashMap<String, Object>();
            map.put("title",successNewsXm.getTitle());
            map.put("district_news_id", successNewsXm.getDistrictNewsId());
            map.put("successful_time", successNewsXm.getSuccessful_time());
            map.put("provinceId",successNewsXm.getProvince());
            map.put("cityId",successNewsXm.getCity());
            map.put("win_bid_figure",successNewsXm.getWin_bid_figure());
            /* 提取摘要时，用到正文 */
//            map.put("content",successNewsXm.getContent());

            map.put("stime",Integer.parseInt(successNewsXm.getStime())<0?"0":successNewsXm.getStime());
            map.put("starTime", DateUtil.getStringDate(Integer.parseInt(map.get("stime") + ""), "yyyy-MM-dd"));
            String district="";
            if(Integer.parseInt(map.get("provinceId").toString())>100000){
                district+=locationService.getLocationMap().get(map.get("provinceId").toString());
                if(Integer.parseInt(map.get("cityId").toString())>0){
                    String city=locationService.getLocationMap().get(map.get("cityId").toString())+"";
                    if(!city.equals("null") && !city.equals("")) {
                        district += "  " +city;
                    }
                }
            /* 返回数据前对没有地域的地区进行地域处理 */
            }else{
                int t_code= GetLocationFromTitle.getLocation(map.get("title").toString());
                if(t_code!=0 ){
                    if(t_code%10000==0){
                        map.put("provinceId",t_code);
                        district+=locationService.getLocationMap().get(map.get("provinceId").toString());
                    }else{
                        map.put("cityId",t_code);
                        map.put("provinceId", t_code/10000*10000);
                        district+=locationService.getLocationMap().get(map.get("provinceId").toString());
                        district+=" "+locationService.getLocationMap().get(map.get("cityId").toString());
                    }
                }
            }
            map.put("district",district);

            listNews.add(map);
        }
        return listNews;
    }

}
